<?php

class Controller_Manage_Product_Edit extends Controller_Manage_Abstract
{
	function execute($request)
	{
		$form = new Form_Product_Create;

		$id = intval($request -> getParam('_id'));

		if($id){
			$product = Mongo_Document::factory('product', $id);
		}
		if ($id && $request -> isGet())
		{
			$product -> load();
			$form -> setValues($product -> as_array());
		}

		if ($id && $request -> isPost())
		{
			if ($request -> isPost())
			{
				// check temporary file if exists, what will be happend.
				$temp = Upload::makeTemporaryFile('photo');

				if ($form -> isValid($_POST))
				{
					$values = $form -> getValues();

					$product -> name = $values['name'];
					$product -> tags = $values['tags'];
					$product -> updated_at = time();
					$product -> deals = $values['deals'];
					$product -> price = doubleval($values['price']);

					if ($temp)
					{
						$product -> photo = $temp;
					}

					$product -> posted_by = Agilet::getViewer() -> _id;
					$product -> manufactor = $values['manufactor'];
					$product -> description = $values['description'];
					$product->save();
					
					$form->setNotice('Cập nhật sản phẩm thành công!');	
				}
			}
		}

		$data = array('form' => $form);

		$request -> response = View::render($data, 'controller/manage/edit.tpl');
	}

}
